package com.pro.admin.web.guanwang;


import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pro.admin.annotation.RequiresPermissionsDesc;
import com.pro.admin.web.BaseController;
import com.pro.core.util.JacksonUtil;
import com.pro.core.util.ResponseUtil;
import com.pro.core.validator.NotNullValidator;
import com.pro.db.domain.GuopuSetting;
import com.pro.db.service.itf.IGuopuBannerService;
import com.pro.db.service.itf.IGuopuCategoryRichtextService;
import com.pro.db.service.itf.IGuopuCategoryService;
import com.pro.db.service.itf.IGuopuSettingService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toComplex;

/**
 * <p>
 * 设置表 前端控制器
 * </p>
 *
 * @author wanglei
 * @since 2019-12-22
 */
@RestController
@RequestMapping("/admin/setting")
public class GuopuSettingController extends BaseController {
    private final Log logger = LogFactory.getLog(GuopuSettingController.class);

    @Autowired
    private IGuopuCategoryRichtextService richtextService;

    @Autowired
    private IGuopuCategoryService categoryService;

    @Autowired
    private IGuopuSettingService settingService;

    @Autowired
    private IGuopuBannerService bannerService;

    /**
     * @apiDefine setting 设置接口
     *
     */


    /**
     * @api {Get} /admin/setting/getSettings 3.1 获取官网设置
     * @apiName setting getSettings
     * @apiGroup setting
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:setting:getSettings")
    @RequiresPermissionsDesc(menu={"设置管理" , "官网设置"}, button="获取官网设置")
    @GetMapping("/getSettings")
    public Object getSettings() {
        List<GuopuSetting> settings = settingService.list(new QueryWrapper<GuopuSetting>()
            .eq("setting_type",1)
            .eq("deleted",0));
        return ResponseUtil.ok(settings);
    }

    /**
     * @api {POST} /admin/setting/updateSettings 3.2 更新官网设置
     * @apiName setting updateSettings
     * @apiGroup setting
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷 <br/>
     * admin_guanwang_logo  官网logo <br/>
     * admin_guanwang_background  官网背景图 <br/>
     * admin_guanwang_content  官网中间内容 <br/>
     *
     * @apiParam {String} body 设置键值对，以map形式
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:setting:updateSettings")
    @RequiresPermissionsDesc(menu={"设置管理" , "官网设置"}, button="更新官网设置")
    @PostMapping("/updateSettings")
    public Object updateSettings(@RequestBody String body) {
        ComplexResult check = FluentValidator.checkAll()
                .on(body, new NotNullValidator("内容"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        Map<String, String> data = JacksonUtil.toMap(body);

        for(Map.Entry<String, String> entry : data.entrySet()){
            GuopuSetting newSetting = settingService.getOne(new QueryWrapper<GuopuSetting>()
                    .eq("setting_key",entry.getKey())
                    .eq("deleted",0));
            if(newSetting == null){
                newSetting = new GuopuSetting();
                newSetting.setAdminId(getCurrentUser().getId());
                newSetting.setAdminName(getCurrentUser().getUsername());
                newSetting.setAddTime(new Date());
                newSetting.setDeleted(false);
                newSetting.setSettingKey(entry.getKey());
                newSetting.setSettingType(1);//官网设置
                newSetting.setSettingName(entry.getKey());
                newSetting.setSettingValue(entry.getValue());
                settingService.save(newSetting);
            }else {
                newSetting.setSettingValue(entry.getValue());
                settingService.updateById(newSetting);
            }
        }
        return ResponseUtil.ok();
    }

    /**
     * @api {Get} /admin/setting/getAppSetting 3.3 获取app设置
     * @apiName setting getAppSetting
     * @apiGroup setting
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:setting:getAppSetting")
    @RequiresPermissionsDesc(menu={"设置管理" , "官网设置"}, button="获取APP设置")
    @GetMapping("/getAppSetting")
    public Object getAppSetting() {
        List<GuopuSetting> settings = settingService.list(new QueryWrapper<GuopuSetting>()
                .eq("setting_type",2)
                .eq("deleted",0));
        return ResponseUtil.ok(settings);
    }

    /**
     * @api {POST} /admin/setting/updateAppSettings 3.4 更新APP设置
     * @apiName setting updateAppSettings
     * @apiGroup setting
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷 <br/>
     * app_home_banner_categoryId:轮播图采用哪个分类的轮播图 <br/>
     * app_home_bottom_categoryId:底部中央展示哪个一级栏目 <br/>
     * app_home_btn_one_categoryId: 第一个按钮的一级或二级栏目<br/>
     * app_home_btn_two_categoryId: 第二个按钮的一级或二级栏目<br/>
     * app_home_btn_three_attr: 第三个按钮的图标及名字，做json上传<br/>
     * app_home_btn_four_attr: 第四个按钮的图标及名字，做json上传<br/>
     *
     * @apiParam {String} body 设置键值对，以map形式
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:setting:updateAppSettings")
    @RequiresPermissionsDesc(menu={"设置管理" , "官网设置"}, button="更新APP设置")
    @PostMapping("/updateAppSettings")
    public Object updateAppSettings(@RequestBody String body) {
        ComplexResult check = FluentValidator.checkAll()
                .on(body, new NotNullValidator("内容"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        Map<String, String> data = JacksonUtil.toMap(body);

        for(Map.Entry<String, String> entry : data.entrySet()){
            GuopuSetting newSetting = settingService.getOne(new QueryWrapper<GuopuSetting>()
                    .eq("setting_key",entry.getKey())
                    .eq("deleted",0));
            if(newSetting == null){
                newSetting = new GuopuSetting();
                newSetting.setAdminId(getCurrentUser().getId());
                newSetting.setAdminName(getCurrentUser().getUsername());
                newSetting.setAddTime(new Date());
                newSetting.setDeleted(false);
                newSetting.setSettingKey(entry.getKey());
                newSetting.setSettingType(2);//APP设置
                newSetting.setSettingName(entry.getKey());
                newSetting.setSettingValue(entry.getValue());
                settingService.save(newSetting);
            }else {
                newSetting.setSettingValue(entry.getValue());
                settingService.updateById(newSetting);
            }
        }
        return ResponseUtil.ok();
    }
}

